package com.kfm.storage.watcher;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Aurora雪
 */
public class DeleteFile {
    public static void deleteFileFromRemoteServer(String fileName, String remoteIpAddress, int remotePort, String requestIdentifier) {
        // 创建一个线程用来删除远程服务器上的文件
        Thread deleteFileThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 创建Socket连接到远程服务器
                    try (Socket socket = new Socket(remoteIpAddress, remotePort)) {
                        // 获取Socket的输出流
                        OutputStream outputStream = socket.getOutputStream();



                        // 发送要删除的文件名到远程服务器
                        // DataOutputStream用来写入基本数据类型的数据
                        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
                       //
                        dataOutputStream.writeUTF(requestIdentifier);

                        // writeUTF()用来写入UTF格式的字符串
                        dataOutputStream.writeUTF(fileName);
                        //writeUTF()用来写入UTF格式的文件扩展名
                        dataOutputStream.writeUTF(fileName.substring(fileName.lastIndexOf(".") + 1));


                        // 关闭Socket连接
                        socket.close();

                        System.out.println("删除文件完成：" + fileName);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        // 启动线程
        deleteFileThread.start();
    }
}
